package com.shop.controller;

import com.shop.common.Constants;
import com.shop.model.User;
import com.shop.service.UserService;
import com.shop.service.impl.UserServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/login")
    public ModelAndView loginPage() {
        return new ModelAndView("user/login");
    }

    @PostMapping("/login")
    public ModelAndView login(@RequestParam(required = false) String phone,
                              @RequestParam(required = false) String email,
                              String password,
                              @RequestParam("loginType") String loginType,
                              HttpSession session) {
        // TODO 校验验证码
        ModelAndView mv = new ModelAndView();
        session.setAttribute(Constants.Session.USER_LOGIN_TYPE, loginType);
        if (loginType.equals("phone")) {
            try {
                log.info("用户登录：username={}", phone);
                User loginUser = userService.login(phone, password);
                session.setAttribute(Constants.Session.USER, loginUser);
                if (loginUser.getUserType()==1) session.setAttribute("userType","admin");
                else session.setAttribute("userType","user");
                session.setMaxInactiveInterval(Constants.Session.SESSION_TIMEOUT);
                mv.setViewName("redirect:/index");
            } catch (Exception e) {
//                mv.addObject("phone", phone);
                mv.addObject("error", e.getMessage());
                mv.setViewName("user/login");
            }
        } else if (loginType.equals("email")) {
            try {
                log.info("用户登录：username={}", email);
                User loginUser = userService.loginEmail(email, password);
                session.setAttribute(Constants.Session.USER, loginUser);
                session.setMaxInactiveInterval(Constants.Session.SESSION_TIMEOUT);
                mv.setViewName("redirect:/index");
            } catch (Exception e) {
//                mv.addObject("email", email);
                mv.addObject("error", e.getMessage());
                mv.setViewName("user/login");
            }
        } else {
            mv.addObject(Constants.Model.ERROR, "请选择登录方式");
        }
        return mv;
    }

    @GetMapping("/register")
    public ModelAndView registerPage() {
        return new ModelAndView("user/register");
    }

    @PostMapping("/register")
    public ModelAndView register(User user,
                                 @RequestParam(required = false) String code,
                                 @RequestParam("registerType") String registerType,
                                 HttpSession session) {
        ModelAndView mv = new ModelAndView();
        if ("phone".equals(registerType)) {
            String sessionCode = (String) session.getAttribute(Constants.Session.REGISTER_PHONE_CODE);
            try {
                log.info("用户注册：username={}", user.getUsername());
                user.setStatus(1);
                if (sessionCode.equals(code)) {
                    userService.register(user);
                    mv.addObject(Constants.Model.MESSAGE, "注册成功，请登录");
                    mv.setViewName("user/login");
                } else {
                    mv.addObject(Constants.Model.ERROR, "验证码错误，请重试！");
                    mv.addObject(Constants.Model.USER, user);
                    mv.setViewName("user/register");
                }
            } catch (Exception e) {
                mv.addObject(Constants.Model.ERROR, e.getMessage());
                mv.addObject(Constants.Model.USER, user);
                mv.setViewName("user/register");
            }
        } else {
            mv.addObject(Constants.Model.ERROR, "请选择注册方式");
        }
        return mv;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constants.Session.USER);
        session.removeAttribute("userType");
        return "redirect:/user/login";
    }

    @GetMapping("/selfInfo")
    public ModelAndView profile(HttpSession session) {
        ModelAndView mv = new ModelAndView();
        User user = (User) session.getAttribute(Constants.Session.USER);
        mv.addObject(Constants.Model.USER, user);
        mv.setViewName("user/selfInfo");
        return mv;
    }

    @PostMapping("/selfInfo")
    public ModelAndView modifyUser(User user,
                                   @RequestParam("action") String action,
                                   @RequestParam("imagePath") String avatar,
                                   HttpSession session,
                                   HttpServletResponse response) {
        User oldUser = (User) session.getAttribute(Constants.Session.USER);
        ModelAndView mv = new ModelAndView();
        if ("save".equals(action)) {
            user.setId(oldUser.getId());
            if (avatar != null) {
                user.setAvatar(avatar);
            }
            user.setPhone(oldUser.getPhone());
            User user1 = userService.modifyUser(user);
            if (user1 == null) {
                mv.addObject(Constants.Model.ERROR, "信息未变化");
                return new ModelAndView("redirect:/index");
            }
            session.setAttribute(Constants.Session.USER, user1);
            mv.addObject(Constants.Model.MESSAGE, "修改成功");
            return new ModelAndView("redirect:/index");
        } else if ("delete".equals(action)) {
//            真实删除该号主的信息
            int a = userService.deleteByPrimaryKey(oldUser.getId());
            if (a <= 0) {
                mv.addObject(Constants.Model.MESSAGE, "注销失败！");
            }
            mv.addObject(Constants.Model.MESSAGE, "注销成功");
            return new ModelAndView("user/login");
        } else {
            mv.addObject(Constants.Model.ERROR, "选择错误，请重试");
            return new ModelAndView("redirect:/index");
        }
    }


    @PostMapping("/changePhone")
    public ModelAndView changePhone(HttpSession session,
                                    @RequestParam("newPhone") String newPhone,
                                    @RequestParam("code") String code) {
        ModelAndView mv = new ModelAndView();
        String sessionCode = (String) session.getAttribute(Constants.Session.REGISTER_PHONE_CODE);
        User sessionUser = (User) session.getAttribute(Constants.Session.USER);
        if (sessionUser.getId() != null) {
            if (sessionCode.equals(code)) {
                //修改电话号码
                userService.changePhone(newPhone, sessionUser);
                sessionUser.setPhone(newPhone);
                session.setAttribute(Constants.Session.USER, sessionUser);
                mv.setViewName("/user/selfInfo");
            } else {
                mv.addObject(Constants.Model.ERROR, "验证码错误，请重试！");
                mv.setViewName("/user/selfInfo");
            }
        } else {
            mv.addObject(Constants.Model.ERROR, "用户未登录，请先登录");
            mv.setViewName("/user/login");
        }
        return mv;
    }

    @PostMapping("/changePassword")
    public ModelAndView changePassword(@RequestParam("oldPassword") String oldPassword,
                                       @RequestParam("password") String password,
                                       @RequestParam("confirmPassword") String confirmPassword,
                                       HttpSession session) {
        // 从 session 获取当前登录用户（假设你用 session 存了登录用户）
        User olduser = (User) session.getAttribute(Constants.Session.USER);
        ModelAndView mv = new ModelAndView();
        if (olduser == null || olduser.getId() == null) {
            mv.addObject(Constants.Model.ERROR, "用户未登录，请先登录");
            mv.setViewName("/user/login");
        }
        userService.getChangPassword(olduser,password,confirmPassword,oldPassword);
        olduser.setPassword(password);
        session.setAttribute(Constants.Session.USER, olduser);
        mv.addObject(Constants.Model.MESSAGE, "密码修改成功");
        mv.setViewName("/user/selfInfo");
        return mv;
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadAvatar(MultipartFile file) throws Exception {
        String url = userService.uplaodAvatar(file);
        return ResponseEntity.ok(url);
    }

    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException {
        Random random = new Random(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();
        char sc = 'a';
        for (int i = 0; i < 4; i++) {
            int str = random.nextInt(62);
            if (str < 10) {
                sb.append(str);
            } else if (str < 36) {
                sc = (char) ((str - 10) + 'a');
                sb.append(sc);
            } else {
                sc = (char) ((str - 36) + 'A');
                sb.append(sc);
            }
        }
        String code = sb.toString();
//        req.getSession().setAttribute("code", code);
        session.setAttribute(Constants.Session.REGISTER_PHONE_CODE, code);
        System.out.println("生成验证码: " + code);
        BufferedImage image = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.GRAY);
        graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font("Time", Font.BOLD, 18));
        graphics.drawString(code, 3, 17);
        // 在 drawString 后加入噪点
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(image.getWidth());
            int y = random.nextInt(image.getHeight());
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            graphics.drawLine(x, y, x, y);
        }
        graphics.dispose();
        resp.setContentType("image/jpeg");
        ImageIO.write(image, "JPG", resp.getOutputStream());
    }
} 